<?php defined('SYSPATH') or die('No direct script access.');

class OrgPerson_Controller extends OrgController {

    private static $DISPLAY_PATH = 'org/orgPerson/display';

    public function __construct() {
        parent::__construct();
        $this->entityName = 'person';
        $this->activeMenuItem = OrgMenu::$PERSONS;
    }

    public function listing() {
    	$query = 'SELECT p.*, c.name AS country_name, acc.login, acc.is_admin, acc.is_blocked ' .
    			'FROM person AS p ' .
    			'LEFT OUTER JOIN account acc ON acc.person_id = p.id ' .
    			'LEFT OUTER JOIN country AS c ON p.country_code = c.code ' .
    			'WHERE p.organization_id = :orgId ';
    	$queryParams = array('orgId' => $this->getAuthOrg('id'));
    	
    	$queryAndParams = new QueryAndParams($query, $queryParams);
    	$this->initPagination($queryAndParams);
    	
    	$this->viewData['personList'] = $this->dao->queryAll($this->orderLimitAndOffset($queryAndParams->query), $queryAndParams->params);
    	
    	$this->renderMySubview('orgPersonList');
    }
    
    /**
     * Default action method.
     */
    public function display() {
        $id = $this->input->get('id');

        if (! valid::isId($id)) {
            $this->redirectToList('error.invalidId');
        }

        $person = $this->dao->fetchPersonById($id);
        if (! $person || $person['organization_id'] != $this->getAuthOrg('id')) {
            $this->redirectToList('error.recordNotFound');
        }

        $this->loadFormData();

        $this->viewData['person'] = $person;
        $this->renderMySubview('orgPersonDisplay');
    }
    
    public function edit() {
    	$id = $this->input->get('id');
    	 
    	if ($id) {
    		$person = $this->dao->fetchPersonById($id);
	    	if (! $person || $person['organization_id'] != $this->getAuthOrg('id')) {
	            $this->redirectToList('error.recordNotFound');
	        }
    	}
    	else {
    		// Set default insert values here
    		$person = array();
    	}
    	 
    	 
    	$this->loadFormData();
    	 
    	$this->viewData['person'] = $person;
    	$this->renderMySubview('orgPersonEdit');
    }
    
    public function loadFormData() {
    	$this->viewData['countryOptions'] = $this->dao->optionsCountry();
    	$this->viewData['idcardTypeOptions'] = form::idcardOptions();
    
    }
    
    public function save() {
    	$person = $this->postToDbValues();
    	$id = $person['id'];
    	 
    	$this->viewData['person'] = $person;
    	 
    	// Basic validation
    	$validator = new EntityValidator($person, 'person', $this->msg);
    	$validator->required('first_name');
    	$validator->required('last_name');
    	$validator->required('gender');
    	$validator->date('birth_date');
    	$validator->required('country_code');
    	$validator->required('country_of_residence_code');
    	$validator->applicationLanguage('preferred_language');
    	if (valid::isIsoDate($person['birth_date'])) {
    		if (seminarHelper::arePapersRequired($person['birth_date'])) {
    			$validator->required('idcard_type');
    			$validator->required('idcard_number');
    		}
    	}
    	 
    	if ($this->msg->hasErrors()) {
    		$this->loadFormData();
    		$this->renderMySubview('orgPersonEdit');
    		return;
    	}
    	 
    	// Database validation
    	if ($id != null) {
    		$existingPerson = $this->dao->fetchPersonById($id);
    		if (! $existingPerson) {
    			logger::securityAlert('Attempt to modify user with non existing ID ' . $id);
    			$this->redirectToList('error.recordNotFound');
    		}
    		else if ($existingPerson['organization_id'] != $this->getAuthOrg('id')) {
    			logger::securityAlert('Attempt to modify the user with ID ' . $id . ' \'' . format::personFullName($existingPerson) . '\' which doesn\'t belong to the organization #' . $this->getAuthOrg('id') . '.');
    			$this->redirectToList('error.recordNotFound');
    		}
    	}
    	$uniqueFields = array ('first_name', 'last_name', 'birth_date');
    	if ($this->dao->alreadyExists('person', $uniqueFields, $person)) {
    		$this->loadFormData();
    		$this->msg->error('person.error-alreadyExists-names');
    		$this->renderMySubview('orgPersonEdit');
    		return;
    	}
    	 
    	// Insert or update the person
    	if ($id != null) {
    		$this->dao->update('person', $person);
    		$this->msg->info('person.editSuccess', format::personFullName($person));
    	}
    	else {
    		$id = $this->dao->insert('person', $person);
    		$this->msg->info('person.createSuccess', format::personFullName($person));
    	}
    	 
    	$this->redirectToList();
    }
    
    public function becomePerson() {
    	$personId = $this->input->get('id');
    
    	// Basic validation
    	if (! $personId) {
    		$this->redirectToList('error.invalidId');
    	}
    
    	$person = $this->dao->getById('person', $personId);
    	if (! $person) {
    		logger::securityAlert('Attempt to become user with non existing ID ' . $personId);
    		$this->redirectToList('error.recordNotFound');
    	}
    	else if ($person['organization_id'] != $this->getAuthOrg('id')) {
    		logger::securityAlert('Attempt to become the user with ID ' . $personId . ' \'' . format::personFullName($person) . '\' who doesn\'t belong to the organization #' . $this->getAuthOrg('id') . '.');
    		$this->redirectToList('error.recordNotFound');
    	}
    
    	$this->getSessionData()->clearUserSpaceData();
    	$this->getSessionData()->setUserSubstitute($person);
    	$this->msg->info('userSpace-substitutionSuccess', format::personFullName($person));
    	$this->redirect('/user/userSpace');
    }
    
    public function cancelSubstitution() {
    	$personSubstitute = $this->getAuthOrSubstituteUser();
    	$this->getSessionData()->clearUserSpaceData();
    	$this->getSessionData()->setUserSubstitute(NULL);
    	$this->msg->info('userSpace-substitutionCancelled');
    	$this->redirect('/org/orgPerson/listing');
    }
}
